<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>成绩管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 老师-->
    <el-form :inline="true" :model="pageQuery" class="user-search" v-if="user.role == '10'">
      <el-form-item label="搜索：">
        <el-select v-model="pageQuery.termId" clearable placeholder="学期">
            <el-option :label="item.describes" :value="item.id" v-for="item in termList" :key="item.id"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="班级：">
       <el-select v-model="pageQuery.classId" clearable placeholder="班级" @change="classChange">
            <el-option :label="item.className" :value="item.classId" v-for="item in classList" :key="item.classId"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="学生名称">
        <el-input size="small" v-model="pageQuery.studentName" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="课程">
        <el-select v-model="pageQuery.courseId" clearable placeholder="课程">
            <el-option :label="item.courseName" :value="item.courseId" v-for="item in courseList" :key="item.courseId"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <a :href="excelHrefTeacher"><el-button size="small" type="warning">导出excel<i class="el-icon-download el-icon--right"></i></el-button></a>
      </el-form-item>
    </el-form>
    <!-- 搜索筛选 管理员-->
    <el-form :inline="true" :model="managerQuery" class="user-search" v-if="user.role == '100'">
      <el-form-item label="搜索：">
        <el-select v-model="managerQuery.termId" clearable placeholder="学期">
            <el-option :label="item.describes" :value="item.id" v-for="item in termList" :key="item.id"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="教师名称">
        <el-input size="small" v-model="managerQuery.teacherName" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="班级名称">
        <el-input size="small" v-model="managerQuery.className" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="课程名称">
        <el-input size="small" v-model="managerQuery.courseName" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="学生名称">
        <el-input size="small" v-model="managerQuery.studentName" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="searchManager">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <a :href="excelHref"><el-button size="small" type="warning">导出excel<i class="el-icon-download el-icon--right"></i></el-button></a>
      </el-form-item>
    </el-form>
    <!-- 搜索筛选 学生-->
    <el-form :inline="true" :model="studentQuery" class="user-search" v-if="user.role == '1'">
      <el-form-item label="搜索：">
        <el-select v-model="studentQuery.termId" clearable placeholder="学期">
            <el-option :label="item.describes" :value="item.id" v-for="item in termList" :key="item.id"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="searchStudent">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-button type="warning" :disabled="!publishStatus" v-if="user.role == '10'" style="margin-bottom:10px" @click="fabu">发布成绩</el-button>
    <el-table size="small" ref="userTable" :data="userList" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <!-- <el-table-column align="center" type="selection" width="60">
      </el-table-column> -->
      <el-table-column v-if="user.role == '1' || user.role == '100'" align="center" prop="termName" label="学期" width="200">
      </el-table-column>
      <el-table-column v-if="user.role == '10'" align="center" prop="name" label="学生姓名" width="200">
      </el-table-column>
      <el-table-column v-if="user.role == '1' || user.role == '100'" align="center" prop="studentName" label="学生姓名" width="150">
      </el-table-column>
      <el-table-column v-if="user.role == '1' || user.role == '100'" align="center" prop="courseName" label="课程名" width="150">
      </el-table-column>
      <el-table-column v-if="user.role == '1' || user.role == '100'" align="center" prop="teacherName" label="教师名" width="150">
      </el-table-column>
      <el-table-column align="center" prop="className" label="班级" width="200">
      </el-table-column>
      <el-table-column v-if="user.role == '1' || user.role == '100'" align="center" prop="scores" label="成绩（分）" width="200">
        <template slot-scope="scope">
          {{scope.row.scores * 100}}
        </template>
      </el-table-column>
      <el-table-column v-if="user.role == '10'" align="center" prop="courseScore" label="成绩（分）" width="200">
        <template slot-scope="scope">
          {{scope.row.courseScore ? ((scope.row.courseScore * 100) | 0) : returnGrade(scope.row)}}
        </template>
      </el-table-column>
      <el-table-column v-if="user.role == '10'" align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button type="primary" v-if="!scope.row.courseScore" size="mini" @click="record(scope.row)">录入</el-button>
          <el-button type="warning" v-if="scope.row.courseScore" size="mini" @click="changeRecord(scope.row)">修改成绩</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-if="user.role == '10'" v-bind:child-msg="pageQuery" :total="total" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog title="成绩录入" :visible.sync="gradeDialog" width="40%" @click="closeDialog">
      <el-form label-width="120px" ref="editForm">
        <el-form-item label="学生姓名：" prop="recordQuery.studentName">
          <el-input size="small" v-model="recordQuery.studentName" auto-complete="off" disabled readonly></el-input>
        </el-form-item>
        <el-form-item label="班级：" prop="recordQuery.className">
          <el-input size="small" v-model="recordQuery.className" disabled readonly auto-complete="off"></el-input>
        </el-form-item>
        <h2>录入</h2>
        <el-form-item :label="item.describes+'：'" v-for="(item, index) in gradeDetail.gradeList" :key="index">
          <el-input-number v-model="scoresTmp[index]" :min="1" :max="100"></el-input-number><span style="margin-left:10px">（分数占比{{item.scale}}%）</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog title="成绩修改申请" :visible.sync="changeDialog" width="40%" @click="changeDialog=false">
      <el-form label-width="120px" ref="editForm">
        <el-form-item label="学生姓名：" prop="changeRecordQuery.studentName">
          <el-input size="small" v-model="changeRecordQuery.studentName" auto-complete="off" disabled readonly></el-input>
        </el-form-item>
        <el-form-item :label="item.describes+'：'" v-for="(item, index) in gradeDetail.gradeList" :key="index">
          <el-input-number v-model="scoresTmp1[index]" :min="1" :max="100"></el-input-number><span style="margin-left:10px">（分数占比{{item.scale}}%）</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="changeDialog=false">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="sureChangeRecord">提交申请</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import Pagination from '../../components/Pagination'
export default {
  name:'UserDetail',
  data() {
    return {
      gradeDetail: { // grade dialog
        courseName: '',
        gradeList: []
      },
      managerQuery: { // 管理员查询参数
        termId: "",
        teacherName: "",
        className: "",
        courseName: "",
        studentName: "",
        pageNum: 1,
        pageSize: 10
      },
      studentQuery: { // 学生查询参数
        termId: '',
        studentId: '',
        pageNum: 1,
        pageSize: 10
      },
      recordQuery: { // 新增录入
        classId: '',
        teacherId: '',
        courseId: '',
        studentId: '',
        scores: 0,
        studentName: '',
        className: ''
      },
      changeRecordQuery: { // 修改成绩
        studentId: '',
        courseId: '',
        scores: 0,
        studentName: ''
      },
      scoresTmp: [], // 录入分数临时缓存区
      scoresTmp1: [], // 修改分数临时缓存区
      changeDialog: false, // 成绩修改dialog
      gradeDialog: false, // 成绩录入dialog
      classList: [], // 老师角色 该老师下属班级集合
      courseList: [], // 老师角色 该老师下属班级对应的课程集合
      userList: [], // 学生列表
      termList: [], // 学期列表
      pageQuery: {
        termId: '',
        teacherId: '',
        studentName: '',
        courseId: '',
        classId: '',
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      loading: false, //是显示加载
      // rules表单验证
      rules: {
        name: [
          { required: true, message: '请输入成绩昵称', trigger: 'blur' }]
      }
    }
  },
  // 注册组件
  components: {
    Pagination
  },
  created() {
    if (this.user.role == '10') {
      this.setPublishStatus(false)
      this.setGradeLocal([])
      this.getTermList()
    } else if (this.user.role == '100') {
      this.getTermList()
    } else {
      this.getTermList()
    }
  },
  computed: {
    ...mapState(['user', 'publishStatus', 'gradeLocal']),
    excelHref () {
      return `http://47.103.5.136:9669/api/scores/downloadExcel?termId=${this.managerQuery.termId}&teacherName=
      ${this.managerQuery.teacherName}&className=${this.managerQuery.className}
      &courseName=${this.managerQuery.courseName}&studentName=${this.managerQuery.studentName}
      &pageNum=${this.managerQuery.pageNum}&pageSize=-1`
    },
    excelHrefTeacher () {
      return `http://47.103.5.136:9669/api/scores/downloadExcelForTeacher?termId=${this.pageQuery.termId}
      &teacherId=${this.user.id}&classId=${this.pageQuery.classId}&courseId=${this.pageQuery.courseId}
      &studentName=${this.pageQuery.studentName}&pageNum=${this.pageQuery.pageNum}&pageSize=-1`
    }
  },
  methods: {
    ...mapMutations(['setPublishStatus', 'setGradeLocal']),
    /**
     * 获取学期列表
     */
    getTermList() {
      let query = {
        pageNum: 1,
        pageSize: -1
      }
      this.$api.course.getTermList(query).then(res => {
        if (res.code === 200) {
          this.termList = res.data.records
          let curTermId = res.data.records.filter(item => item.status)[0].id
          if (this.user.role == '100') {
            this.managerQuery.termId = curTermId
            this.managerGetGradeList()
          } else if (this.user.role == '1') {
            this.studentQuery.termId = curTermId
            this.studentQuery.studentId = this.user.id
            this.studentGetGradeList()
          } else {
            this.pageQuery.termId = curTermId
            this.searchTeacherCourse()
          }
        }
      })
    },
    /**
     * 管理员查询成绩
     */
    managerGetGradeList () {
      this.$api.course.managerGetGradeList(this.managerQuery).then(res => {
        if (res.code === 200) {
          this.userList = res.data
          // this.total = res.data.total
        }
      })
    },
    /**
     * 管理员搜索
     */
    searchManager () {
        this.managerGetGradeList()
    },
    /**
     * 管理员到处excel
     */
    download () {
      this.$api.auth.download(this.managerQuery).then(res => {
        if (res.code === 200) {
        }
      })
    },
    /**
     * 学生搜索
     */
    searchStudent () {
      this.studentGetGradeList()
    },
    /**
     * 学生查询成绩
     */
    studentGetGradeList () {
      this.$api.course.studentGetGradeList(this.studentQuery).then(res => {
        if (res.code === 200) {
          this.userList = res.data
          // this.total = res.data.total
        }
      })
    },
    /**
     * 修改成绩 dialog
     */
    changeRecord (row) {
      this.checkIfStructure()
      this.changeDialog = true
      this.changeRecordQuery.studentName = row.name
      this.changeRecordQuery.courseId = this.pageQuery.courseId
      this.changeRecordQuery.studentId = row.id
      this.changeRecordQuery.scores = row.courseScore * 100
    },
    /**
     * 修改成绩 api
     */
    sureChangeRecord () {
      this.changeRecordQuery.scores = 0
      delete this.changeRecordQuery.studentName
      this.scoresTmp1.forEach((cur, index) => {
        this.gradeDetail.gradeList.forEach((item, index1) => {
            if (index === index1) {
             this.changeRecordQuery.scores += Number(cur) * (item.scale / 100)
            }
          })
      })
      this.changeRecordQuery.scores = this.changeRecordQuery.scores / 100
      this.$api.course.changeRecord(this.changeRecordQuery).then(res => {
        if (res.code === 200) {
          this.changeDialog = false
          this.$message.success('修改申请已提交')
          this.scoresTmp1 = []
        }
      })
    },
    /**
     * 本地编辑状态处理
     */
    returnGrade (row) {
      let arr = this.gradeLocal.map(item => item.studentId)
      console.log(arr);
      if (arr.length > 0) {
        let ind = arr.findIndex(item => item == row.id)
        if (ind > -1) {
          return (this.gradeLocal[ind].scores * 100) | 0
        } else {
          return '尚未录入'
        }
      } else {
        return '尚未录入'
      }
    },
    /**
     * 成绩录入 本地
     */
    submitForm () {
      this.setPublishStatus(true)
      delete this.recordQuery.studentName
      delete this.recordQuery.className
      this.scoresTmp.forEach((cur, index) => {
        this.gradeDetail.gradeList.forEach((item, index1) => {
          if (index === index1) {
            this.recordQuery.scores += Number(cur) * (item.scale / 100)
          }
        })
      })
      this.recordQuery.scores = this.recordQuery.scores / 100
      console.log(this.recordQuery);
      let lp = {
        ...this.recordQuery,
        scoresTmp: this.scoresTmp
      }
      this.$message.success('已记录本学生成绩，等待发布')
      this.setGradeLocal(lp)
      console.log(this.gradeLocal);
      this.closeDialog()
      // this.$refs.userTable.doLayout()
      this.$api.course.searchStudentList(this.pageQuery).then(res => {
          if (res.code === 200) {
            this.userList = res.data.records
            // let flag = res.data.records.some(item => !courseScore)
            // if (flag) {
            //   this.setPublishStatus(true)
            //   this.setGradeLocal([])
            // } else {
            //   this.setPublishStatus(false)
            //   this.setGradeLocal([])
            // }
            // this.total = res.data.total
            // this.loading = false
          }
        })
    },
    /**
     * 正式 录入成绩 fabu
     */
    fabu () {
      let waitList = this.userList.filter(item => !item.courseScore)
      if (this.gradeLocal.length !== waitList.length) {
        let flag = []
        let lcoalArr = this.gradeLocal.map(item => item.studentId)
        console.log(lcoalArr);
        this.userList.forEach(item => {
          if (!lcoalArr.includes(item.id)) {
            flag.push(item.name)
          }
        })
        console.log(flag);
        this.$message({
          type: 'warning',
          message: `学生${flag.join(',')}暂未录入成绩`
        })
      } else {
        this.$api.course.recordGrade(this.gradeLocal).then(res => {
          if (res.code === 200) {
            this.$message.success('成功发布成绩')
            this.searchStudentList()
          }
        })
      }
    },
    /**
     * 录入成绩 先判是否有分数结构 ? 请求分数结构接口 : 提示
     */
    record (row) {
      this.checkIfStructure(1)
      this.recordQuery.studentName = row.name
      this.recordQuery.className = row.className
      this.recordQuery.classId = row.classId
      this.recordQuery.studentId = row.id
      this.recordQuery.teacherId = this.user.id
      this.recordQuery.scores = 0
      let tmp = []
      if (this.gradeLocal.length>0) {
        tmp = this.gradeLocal.filter(item => item.studentId == row.id)
        console.log(tmp);
        if (tmp.length > 0 && Object.keys(tmp[0]).length > 0) {
          this.scoresTmp = tmp[0].scoresTmp
        }
      }
    },
    /**
     * 查询该门课程是否有分数结构 ? 200 : 400
     */
    checkIfStructure (type = 0) {
      this.recordQuery.courseId = this.pageQuery.courseId
      let query = {
        courseId: this.pageQuery.courseId
      }
      this.$api.course.checkIfStructure(query).then(res => {
        if (res.code === 200) {
          this.getTeacherCourseDetail(this.pageQuery.courseId, type)
        }
      })
    },
    /**
     * 如果有分数结构 则返回
     */
    getTeacherCourseDetail (id, type) {
      let query = {
        courseId: id
      }
      this.$api.course.getTeacherCourseDetail(query).then(res => {
        if (res.code === 200) {
          this.gradeDetail.gradeList = res.data.scoreStructureList.map(item => {
            return {
              describes: item.describes,
              scale: Number(item.scale) * 100
            }
          })
          if (type) {
            this.gradeDialog = true
          }
        }
      })
    },
    /**
     * 班级更改导致的课程更改
     */
    classChange (e) {
      this.pageQuery.courseId = ''
      this.courseList = this.classList.map(item => {
        if (e == item.classId) {
          return item.courseList
        }
      }).filter(item => item)[0]
    },
    /**
     * 查询指定教师的授课安排
     */
    searchTeacherCourse () {
      let query = {
        teacherId: this.user.id
      }
      this.$api.course.searchTeacherCourse(query).then(res => {
        if (res.code === 200) {
          this.classList = res.data
          if (res.data && res.data.length !== 0) {
            this.pageQuery.classId = res.data[0].classId
            this.pageQuery.courseId = res.data[0].courseList[0].courseId
            this.courseList = res.data[0].courseList
            this.searchStudentList()
          }
        }
      })
    },
    /**
     * 搜索
     */
    search () {
      this.searchStudentList()
    },
    /**
     * 获取学生列表
     */
    searchStudentList() {
      this.pageQuery.teacherId = this.user.id
      if (!this.pageQuery.courseId) {
        this.$message.warning('请选择课程')
      } else {
        this.loading = true
        this.$api.course.searchStudentList(this.pageQuery).then(res => {
          if (res.code === 200) {
            this.userList = res.data.records
            this.setPublishStatus(false)
            this.setGradeLocal([])
            this.gradeLocal = []
            this.total = res.data.total
            this.loading = false
          }
        }).catch(err => this.loading = false)
      }
    },
    /**
     * 分页插件事件
     */
    callFather(parm) {
      this.pageQuery.pageNum = parm.currentPage
      this.pageQuery.pageSize = parm.pageSize
      this.searchStudentList()
    },
    /**
     * 关闭弹框
     */
    closeDialog () {
      this.scoresTmp = []
      this.gradeDialog = false
    }
  }
}
</script>

<style>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

 
 